<?php

namespace app\zhongcan\controller;

use api\web\model\BannerModel;
use cmf\controller\AdminBaseController;
use think\Request;

class BannerController extends AdminBaseController
{
    //页面
    public function index(Request $request)
    {
        $name = $request->get('name');
        $where = [];
        if ($name) {
            $where[] = ['title','like','%'.$name.'%'];
        }
        $res = BannerModel::order('id','desc')
            ->where($where)
            ->paginate(3);
        $this->assign('list',$res);
        return $this->fetch('banner/index');
    }

    //添加内容
    public function add()
    {
        return $this->fetch('banner/add');
    }
    //提交添加
    public function addPost()
    {
        $image = $_POST['image'];
        $image = cmf_get_image_url($image);
        $res = BannerModel::create([
           'url' => '#',
           'image' => $image
        ]);
        if ($res) {
            return $this->success('添加成功');
        }else{
            return $this->error('添加失败');
        }
    }

    //修改内容
    public function edit(Request $request)
    {
        $id = $request->param('id');
        $res = BannerModel::where('id','=',$id)
            ->find();
        $this->assign('res',$res);
        return $this->fetch('banner/edit');
    }

    //删除
    public function delete(Request $request)
    {
        $id = $request->param('id/d');
        $list = BannerModel::where('id',$id)
            ->delete();
        if ($list) {
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    //是否展示
    public function show(Request $request)
    {
        $id = $request->param('id/d');
        $list = BannerModel::where('id',$id)->find();

        if ($list['switch'] == 1) {
            $list['switch'] = 0;
        }else{
            $list['switch'] = 1;
        }
        $res = BannerModel::where('id','=',$id)
            ->update([
                'switch'=>$list['switch']
            ]);
        if ($res) {
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }
    }
}